<script lang="ts" setup>
import type { DictModel } from '#/api/system/models';

import { useVbenModal } from '@vben/common-ui';

import { Button, Popconfirm, Tag } from 'ant-design-vue';

import {
  useVbenVxeGrid,
  type VxeGridListeners,
  type VxeGridProps,
} from '#/adapter/vxe-table';
import { deleteDictApi, getDictPagedListApi } from '#/api/system/dict';

import DictTypeFormModal from './dict-type-form.vue';

defineOptions({ name: 'SystemDictType' });

const selected = defineModel<DictModel>('selected');

const gridOptions: VxeGridProps<DictModel> = {
  columns: [
    { type: 'seq', width: 60 },
    { field: 'name', title: '字典名称', minWidth: 160 },
    { field: 'code', title: '字典编码', minWidth: 160 },
    { field: 'status', title: '状态', width: 80, slots: { default: 'status' } },
    { field: 'order', title: '排序', width: 80 },
    {
      field: 'action',
      title: '操作',
      fixed: 'right',
      width: 140,
      slots: { default: 'action' },
    },
  ],
  border: true,
  height: 'auto',
  rowConfig: {
    isHover: true,
    isCurrent: true,
  },
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        return await getDictPagedListApi({
          pageNumber: page.currentPage,
          pageSize: page.pageSize,
        });
      },
    },
  },
};

const gridEvents: VxeGridListeners<DictModel> = {
  cellClick: ({ row }) => {
    selected.value = row;
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ gridEvents, gridOptions });

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: DictTypeFormModal,
});

function openFormModal(row?: DictModel) {
  formModalApi.setData({ values: row });
  formModalApi.open();
}

async function deleteHandle(row: DictModel) {
  await deleteDictApi(row.id);
  gridApi.reload();
}
</script>

<template>
  <Grid>
    <template #toolbar-actions>
      <Button type="primary" @click="openFormModal()"> 新增 </Button>
    </template>
    <template #status="{ row }">
      <Tag :color="row.status === 1 ? 'green' : 'red'">
        {{ row.status === 1 ? '启用' : '停用' }}
      </Tag>
    </template>
    <template #action="{ row }">
      <Button size="small" type="link" @click="openFormModal(row)">
        编辑
      </Button>
      <Popconfirm title="确定要删除吗？" @click="deleteHandle(row)">
        <Button size="small" type="link"> 删除 </Button>
      </Popconfirm>
    </template>
  </Grid>
  <FormModal @complete="() => gridApi.reload()" />
</template>
